# coding=utf-8
from __future__ import print_function

# -----------------------------------------------------------------------
import ida_kernwin
import ida_name
import ida_idaapi
import idc
try:
    import requests
except:
    ida_kernwin.warning('requests package not installed')
import json



class msdnapihelp_plugin_t(ida_idaapi.plugin_t):
    flags = ida_idaapi.PLUGIN_UNL
    comment = "Online Test"
    help = "Help me"
    wanted_name = "Online Test Wanted Name"
    wanted_hotkey = "F3"

    def init(self):
        return ida_idaapi.PLUGIN_OK


    


    def run(self, arg):

        is_valid_selection, start_ea, end_ea = ida_kernwin.read_range_selection(None)


        if start_ea == idc.BADADDR or end_ea == idc.BADADDR:
            ida_kernwin.msg("No code selected!")
            return


        code_lines = []
        ea  = start_ea
        while ea < end_ea:
            #print(hex(ea),idc.GetDisasm(ea))
            code_lines.append(idc.GetDisasm(ea))
            ea = idc.next_head(ea)
        ident = "\n".join(code_lines)
        print(ident)
        ###########################################ollama#########################################
        url = "http://127.0.0.1:11434/api/chat"
        model = "phi3:latest"
        headers = {"Content-Type": "application/json"}
        content = ident
        data = {
                "model": model, 
                "options": {
                    "temperature": 0.  
                },
                "stream": False, 
                "messages": [{
                    "role": "system",
                    "content":content+"The translation of the sentence is:Basic function of the code: xxxx, code considerations: xxxx. The output result please use the Chinese"
                }]
            }
        ###########################################ollama#########################################
        response=requests.post(url,json=data,headers=headers,timeout=60)
        res=response.json()
        d = res['message']['content']
        # result = requests.get("https://www.baidu.com")
        # d = result.text
        # d = ident
        ref = idc.get_screen_ea()
        
        #d = str(d).decode("utf-8")  # Convert unicode to string
        if len(d) > 0:
            d = d.encode('utf-8')
            print(d)
            idc.MakeComm(ref, d)
        else:
            print("The response is empty.")
        


    def term(self):
        pass


# -----------------------------------------------------------------------
def PLUGIN_ENTRY():
    return msdnapihelp_plugin_t()